//
//  SentenceDB.m
//  DialectShare
//
//  Created by timmy zhong on 4/4/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SentenceDB.h"
#import "Const.h"
#import "FMDatabase.h"
#import "PathHelper.h"
#import "Sentence.h"

@implementation SentenceDB


- (id)init
{
    self = [super init];
    if (self) {
        FMDatabase *db = [FMDatabase databaseWithPath:[PathHelper dbPath]];
        if ([db open]) {
            NSString* createTableStatement = [NSString stringWithFormat:
                                              @"""CREATE TABLE IF NOT EXISTS %@"""
                                              """(%@ INTEGER PRIMARY KEY, %@ INTEGER, %@ INTEGER, %@ TEXT)""", 
                                              SentenceTable, SentenceId, SentenceUid, SentenceCount, SentenceContent];
            BOOL su = [db executeUpdate:createTableStatement]; 
            if (!su) {
                NSLog(@"fail to create table  %@  error  %@", SentenceTable, [db lastErrorMessage]);
            }
            [db close];
        }
    }
    
    return self;
}

- (void)addSentences:(NSArray *)sentences
{
    FMDatabase *db = [FMDatabase databaseWithPath:[PathHelper dbPath]];
    if (![db open]) {
        NSLog(@"addSentences: fail to open DB error  %@", [db lastErrorMessage]);
        return;
    }
    
    [db beginTransaction];
    for (Sentence *s in sentences) {
        
        NSString *sql = [NSString stringWithFormat:@"INSERT OR REPLACE INTO %@ (%@, %@, %@, %@) values (?, ?, ?, ?)", SentenceTable , SentenceId, SentenceUid, SentenceCount, SentenceContent];
        [db executeUpdate:sql,
         [NSNumber numberWithInt:s.sentenceId],
         [NSNumber numberWithInt:s.uid],
         [NSNumber numberWithInt:s.count],
         s.content];
    }
    
    BOOL su = [db commit];
    if (!su) {
        NSLog(@"fail to add sentences error %@", [db lastErrorMessage]);
    }
    [db close];

}

- (NSArray *)condition:(NSString *)condition start:(NSInteger)start count:(NSInteger)count
{
    FMDatabase *db = [FMDatabase databaseWithPath:[PathHelper dbPath]];
    if (![db open]) {
        NSLog(@"getSentences: fail to open DB error  %@", [db lastErrorMessage]);
        return nil;
    }
    
    NSString *sql = [NSString stringWithFormat:@"select * from %@ where %@ order by %@ desc limit %d, %d", SentenceTable, condition, SentenceCount, start, count];
    FMResultSet *rs = [db executeQuery:sql];
    NSMutableArray *sentences = [[NSMutableArray alloc] initWithCapacity:20];
    while ([rs next]) {
        Sentence *s = [[Sentence alloc] init];
        s.sentenceId = [rs intForColumn:SentenceId];
        s.content = [rs stringForColumn:SentenceContent];
        s.count = [rs intForColumn:SentenceCount];
        s.uid = [rs intForColumn:SentenceUid];
        [sentences addObject:s];
        [s release];
    }
    [db close];
    return [sentences autorelease];
}















@end
